from pynput import keyboard, mouse

# 初始化一个锁，以确保线程安全地打印输出
import threading

# 定义要模拟鼠标的键盘按键（例如，F1 模拟左键按下）
KEY_MAPPING = {
    keyboard.Key.ctrl_r: mouse.Button.right,
    # 你可以根据需要添加更多按键映射，例如：
    # keyboard.Key.f2: mouse.Button.right,
    # keyboard.Key.f3: mouse.Button.middle,
}

# 当前模拟的鼠标按钮状态
current_buttons = set()

# 创建鼠标控制器
mouse_controller = mouse.Controller()

def on_press(key):
    try:
        print(f'{key.char} pressed')
    except AttributeError:
        print(f'{key} pressed')

    if key in KEY_MAPPING:
        btn = KEY_MAPPING[key]
        current_buttons.add(btn)
        mouse_controller.press(btn)
        print(f"按下 {key}，模拟鼠标 {btn} 按下")

def on_release(key):
    print(f'{key} released')
    # 如果按下 Esc 键，则停止监听
    # if key == keyboard.Key.esc:
    #     return False

    if key in KEY_MAPPING:
        btn = KEY_MAPPING[key]
        current_buttons.discard(btn)
        mouse_controller.release(btn)
        print(f"释放 {key}，模拟鼠标 {btn} 释放")

def on_click(x, y, button, pressed):
    action = "Pressed" if pressed else "Released"
    print(f'Mouse {action} at ({x}, {y}) with {button}')

def on_scroll(x, y, dx, dy):
    direction = "down" if dy < 0 else "up"
    print(f'Mouse scrolled at ({x}, {y}) ({direction})')

# 创建键盘监听器
keyboard_listener = keyboard.Listener(on_press=on_press, on_release=on_release)

# 创建鼠标监听器
mouse_listener = mouse.Listener(on_click=on_click, on_scroll=on_scroll)

# 启动监听器
print("按键和鼠标监听已启动。按 Esc 键停止程序。")
keyboard_listener.start()
mouse_listener.start()

# 等待监听器结束
keyboard_listener.join()
mouse_listener.join()
